package fpt.myFileHandler;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.rtf.RTFEditorKit;


/**
 * RTFHandler
 * 
 * r25
 * 
 * 12 March 2010
 * 
 * The RTFHandler class uses the RTFEditorKit to process the input file
 * in order to get rid of unnecessary formatting information found at
 * the start of the file and unnecessary characters found at the end
 * of each line.
 * @author Daniel De Guzman
 */
public class RTFHandler extends Handler {
	private String[] processedInput;
	private int k;
	private int vCount;
	private String[] vInfoArray;
	private String error;

	/**
	 * RTFHandler Constructor
	 * @param in - Rich Text Format File
	 * @throws IOException
	 * @throws BadLocationException
	 */
	public RTFHandler(FileReader in) throws IOException, BadLocationException {
		this.processedInput = this.processInput(in); 
		this.k = Functions.getValue(processedInput, 0);
		this.vCount = Functions.getValue(processedInput,1);
		this.vInfoArray = new String[processedInput.length-2];
		System.arraycopy(processedInput, 2, vInfoArray, 0, vInfoArray.length);
		this.setError("");
	}
	
	/**
	 * Removes unnecessary formatting information found in RTF Files
	 * @param in - RTF file
	 * @return String[]
	 * @throws IOException
	 * @throws BadLocationException
	 */
	String[] processInput(FileReader in) throws IOException, BadLocationException {
		RTFEditorKit rtf = new RTFEditorKit();
		DefaultStyledDocument doc = new DefaultStyledDocument();
		rtf.read(in, doc, 0);
		
		String contents = doc.getText(0, doc.getLength());
		BufferedReader reader = new BufferedReader(new StringReader(contents));
		String temp = "";
		List<String> output = new ArrayList<String>();
		while ((temp = reader.readLine()) != null)
		{
			output.add(temp);
		}
		return output.toArray(new String[output.size()]);
	}
	
	// GETTERS AND SETTERS
	
	public String[] getProcessedInput(){
		return processedInput;
	}
	
	public int getK() {
		return k;
	}
	
	public void setK(int k) {
		this.k = k;
	}

	public int getvCount() {
		return vCount;
	}
	
	public void setvCount(int vCount) {
		this.vCount = vCount;
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}

	public String[] getvInfoArray() {
		return vInfoArray;
	}

	public void setvInfoArray(String[] vInfo) {
		this.vInfoArray = vInfo;
	}
}
